<template>
  <el-dialog
    v-model="visible"
    title="数据库连接配置"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="left"
    >
      <el-form-item label="数据库类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择数据库类型"
          style="width: 100%"
          @change="onDatabaseTypeChange"
        >
          <el-option label="MySQL" value="mysql" />
          <el-option label="PostgreSQL" value="postgresql" />
        </el-select>
      </el-form-item>

      <el-form-item label="主机地址" prop="host">
        <el-input
          v-model="form.host"
          placeholder="请输入主机地址"
          clearable
        />
      </el-form-item>

      <el-form-item label="端口" prop="port">
        <el-input-number
          v-model="form.port"
          :min="1"
          :max="65535"
          style="width: 100%"
          placeholder="请输入端口号"
        />
      </el-form-item>

      <el-form-item label="数据库名" prop="database">
        <el-input
          v-model="form.database"
          placeholder="请输入数据库名"
          clearable
        />
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          clearable
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item label="连接选项">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-checkbox v-model="form.ssl">启用SSL</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox v-model="form.autoReconnect">自动重连</el-checkbox>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="连接超时">
        <el-input-number
          v-model="form.timeout"
          :min="1000"
          :max="60000"
          :step="1000"
          style="width: 100%"
          placeholder="连接超时时间(毫秒)"
        />
      </el-form-item>
    </el-form>

    <!-- 连接测试结果 -->
    <div v-if="testResult" class="test-result">
      <el-alert
        :title="testResult.message"
        :type="testResult.success ? 'success' : 'error'"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 预设配置 -->
    <div class="preset-configs">
      <el-divider content-position="left">快速配置</el-divider>
      <div class="preset-buttons">
        <el-button
          v-for="preset in presetConfigs"
          :key="preset.name"
          size="small"
          @click="applyPreset(preset)"
        >
          {{ preset.name }}
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="testConnection" :loading="testing">
          测试连接
        </el-button>
        <el-button
          type="primary"
          @click="handleConnect"
          :loading="connecting"
          :disabled="!form.type || !form.host || !form.database"
        >
          连接
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'DatabaseConnection',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'connected'],
  setup(props, { emit }) {
    const formRef = ref()
    const testing = ref(false)
    const connecting = ref(false)
    const testResult = ref(null)

    // 表单数据
    const form = reactive({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      database: '',
      username: 'root',
      password: '',
      ssl: false,
      autoReconnect: true,
      timeout: 10000
    })

    // 表单验证规则
    const rules = {
      type: [
        { required: true, message: '请选择数据库类型', trigger: 'change' }
      ],
      host: [
        { required: true, message: '请输入主机地址', trigger: 'blur' }
      ],
      port: [
        { required: true, message: '请输入端口号', trigger: 'blur' },
        { type: 'number', min: 1, max: 65535, message: '端口号范围1-65535', trigger: 'blur' }
      ],
      database: [
        { required: true, message: '请输入数据库名', trigger: 'blur' }
      ],
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ]
    }

    // 预设配置
    const presetConfigs = ref([
      {
        name: 'MySQL本地',
        config: {
          type: 'mysql',
          host: 'localhost',
          port: 3306,
          username: 'root',
          password: '',
          ssl: false
        }
      },
      {
        name: 'PostgreSQL本地',
        config: {
          type: 'postgresql',
          host: 'localhost',
          port: 5432,
          username: 'postgres',
          password: '',
          ssl: false
        }
      },
      {
        name: 'MySQL开发环境',
        config: {
          type: 'mysql',
          host: '192.168.1.100',
          port: 3306,
          username: 'dev_user',
          password: '',
          ssl: true
        }
      }
    ])

    // 计算属性
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    // 监听数据库类型变化
    const onDatabaseTypeChange = (type) => {
      if (type === 'mysql') {
        form.port = 3306
      } else if (type === 'postgresql') {
        form.port = 5432
      }
      testResult.value = null
    }

    // 应用预设配置
    const applyPreset = (preset) => {
      Object.assign(form, preset.config)
      testResult.value = null
    }

    // 测试连接
    const testConnection = async () => {
      try {
        await formRef.value.validate()
        
        testing.value = true
        testResult.value = null
        
        // 模拟连接测试
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        // 模拟测试结果
        const success = Math.random() > 0.3 // 70% 成功率
        
        testResult.value = {
          success,
          message: success 
            ? `成功连接到 ${form.type.toUpperCase()} 数据库 "${form.database}"` 
            : '连接失败：无法连接到数据库服务器'
        }
        
        if (success) {
          ElMessage.success('连接测试成功')
        } else {
          ElMessage.error('连接测试失败')
        }
      } catch (error) {
        ElMessage.error('请先完善连接信息')
      } finally {
        testing.value = false
      }
    }

    // 连接数据库
    const handleConnect = async () => {
      try {
        await formRef.value.validate()
        
        connecting.value = true
        
        // 模拟连接过程
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 模拟连接成功
        const connectionInfo = {
          type: form.type,
          host: form.host,
          port: form.port,
          database: form.database,
          username: form.username,
          connected: true,
          connectedAt: new Date()
        }
        
        emit('connected', connectionInfo)
        handleClose()
      } catch (error) {
        ElMessage.error('请先完善连接信息')
      } finally {
        connecting.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      testResult.value = null
      // 重置表单验证状态
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    }

    return {
      formRef,
      form,
      rules,
      visible,
      testing,
      connecting,
      testResult,
      presetConfigs,
      onDatabaseTypeChange,
      applyPreset,
      testConnection,
      handleConnect,
      handleClose
    }
  }
}
</script>

<style scoped>
.test-result {
  margin: 16px 0;
}

.preset-configs {
  margin-top: 20px;
}

.preset-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-divider__text) {
  font-size: 14px;
  color: #606266;
}
</style>